<template>
  <div class="register-container">
    <h2 class="form-title">注册</h2>
    <form @submit.prevent="handleRegister">
      <div class="input-group">
        <label for="username">用户名</label>
        <br>
        <input
            type="text"
            id="username"
            v-model="registerForm.username"
            placeholder="请输入用户名"
            required
        />
      </div>
      <div class="input-group">
        <label for="email">邮箱</label>
        <br>
        <input
            type="email"
            id="email"
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            required
        />
      </div>
      <div class="input-group">
        <label for="major">专业</label>
        <br>

        <select
            id="major"
            v-model="registerForm.professional"
            class="major-select"
            required
        >
          <option value="" disabled selected>请选择专业</option>
          <option
              v-for="major in majorOptions"
              :key="major.value"
              :value="major.value"
              style="width: 100%"
          >
            {{ major.label }}
          </option>
        </select>
      </div>
      <div class="input-group">
        <label for="password">密码</label>
        <br>
        <input
            type="password"
            id="password"
            v-model="registerForm.password"
            placeholder="请输入密码"
            required
        />
      </div>
      <div class="input-group">
        <label for="confirmPassword">确认密码</label>
        <br>
        <input
            type="password"
            id="confirmPassword"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
            required
        />
      </div>
      <button type="submit" class="btn">注册</button>
    </form>

    <div class="login-link">
      <p>已有账号？</p>
      <router-link to="/" @click.prevent="handleLoginLink">立即登录</router-link>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { onMounted, onUnmounted } from 'vue';
import axios from "@/api/server";
import router from "@/router";
import { ElMessage } from 'element-plus';

export default {
  name: 'RegisterForm',
  setup() {
    onMounted(() => {
      document.body.classList.add('register_body');
      fetchMajorList(); // 加载专业列表
    });

    onUnmounted(() => {
      document.body.classList.remove('register_body');
    });

    const registerForm = ref({
      username: '',
      email: '',
      professional: '', // 根据接口文档使用professional字段
      password: '',
      confirmPassword: ''
    });

    const majorOptions = ref([]);

    // 获取专业列表
    const fetchMajorList = async () => {
      try {
        const response = await axios.get('/users/majors');
        if (response.data.code === 1 && response.data.data) {
          majorOptions.value = response.data.data.map(item => ({
            value: item.majorName,  // 改为使用majorName
            label: item.majorName
          }));
        } else {
          ElMessage.error('获取专业列表失败：' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取专业列表失败', error);
        ElMessage.error('获取专业列表失败，请稍后重试');
      }
    };

    // 邮箱格式验证
    const isValidEmail = (email) => {
      const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    };

    const handleRegister = async () => {
      // 表单验证
      if (!registerForm.value.username) {
        ElMessage.error('请输入用户名');
        return;
      }
      if (!registerForm.value.email) {
        ElMessage.error('请输入邮箱');
        return;
      }
      if (!isValidEmail(registerForm.value.email)) {
        ElMessage.error('请输入有效的邮箱地址');
        return;
      }
      if (!registerForm.value.professional) {
        ElMessage.error('请选择专业');
        return;
      }
      if (!registerForm.value.password) {
        ElMessage.error('请输入密码');
        return;
      }
      if (registerForm.value.password.length < 6) {
        ElMessage.error('密码长度至少为6位');
        return;
      }
      if (registerForm.value.password !== registerForm.value.confirmPassword) {
        ElMessage.error('两次输入的密码不一致');
        return;
      }

      try {
        // 按照接口文档要求构建请求数据
        const requestData = {
          username: registerForm.value.username,
          email: registerForm.value.email,
          professional: registerForm.value.professional,
          password: registerForm.value.password,
          rePassword: registerForm.value.confirmPassword
        };

        const response = await axios.post("/users/register", requestData, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (response.data.code === 1) {
          // 注册成功后返回用户信息
          const userInfo = {
            username: registerForm.value.username,
            email: registerForm.value.email,
            professional: registerForm.value.professional
          };
          ElMessage.success({
            message: `注册成功！`,
            duration: 5000 // 显示5秒
          });
          router.push('/');
        } else {
          const errorMsg = response.data.msg || '注册失败，请检查输入';
          ElMessage.error(errorMsg);
        }
      } catch (error) {
        console.error('注册请求失败:', error);
        if (error.response) {
          if (error.response.status === 401) {
            ElMessage.error('认证失败：请检查接口权限设置');
          } else {
            ElMessage.error(`请求错误：${error.response.status} ${error.response.statusText}`);
          }
          if (error.response.data && error.response.data.msg) {
            ElMessage.error(`错误详情：${error.response.data.msg}`);
          }
        } else if (error.request) {
          ElMessage.error('服务器未响应，请检查网络连接');
        } else {
          ElMessage.error(`请求配置错误：${error.message}`);
        }
      }
    };

    const handleLoginLink = () => {
      router.push('/');
    };

    return {
      registerForm,
      majorOptions,
      handleRegister,
      handleLoginLink
    };
  }
};
</script>

<style scoped>
@import '../styles/Register.css';
</style>